/*
 * @Author: pardon110
 * @Date: 2024-03-17 10:22:33
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-17 17:10:52
 * @FilePath: \days7\web\router\trie\engine.go
 * @Description:
 */
package trie

import (
	"log"
	"net/http"
)

type HandlerFunc func(*Context)

type Engine struct {
	router *router
}

func New() *Engine {
	return &Engine{router: newRouter()}
}

func (e *Engine) Run(addr string) error {
	return http.ListenAndServe(addr, e)
}

// ServeHTTP 承接上游tcp流
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// 创建组合上下文 并发安全
	c := newContext(w, r)

	// 转发至处理逻辑
	e.router.handle(c)
}

// addRoute  私有隐式添加路由， 转发底层路由实例执行
func (e *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
	log.Printf("Route %4s  - %s", method, pattern)
	e.router.addRoute(method, pattern, handler)
}

// 对外暴露的操作方法
func (engine *Engine) GET(pattern string, handler HandlerFunc) {
	engine.addRoute("GET", pattern, handler)
}

// POST defines the method to add POST request
func (engine *Engine) POST(pattern string, handler HandlerFunc) {
	engine.addRoute("POST", pattern, handler)
}
